import { h, ref } from 'vue';
import SvgIcon from '@/components/svgIcon/index.vue';
import { Modal } from '@arco-design/web-vue';

export function transformDeptTree(
  depts: any,
  parentKey = '0-0',
  idName = 'id'
) {
  return depts.map((dept: any, index: any) => {
    const currentKey = `${parentKey}-${index}`;
    return {
      title: dept.dept_name,
      key: currentKey,
      id: dept[idName],
      icon: () =>
        h(SvgIcon, {
          class: 'icon',
          style: {
            width: '1.2em',
            height: '1.2em',
          },
          name: 'bumen3',
        }),
      children: transformDeptTree(dept.children || [], currentKey, idName),
    };
  });
}

export function transformDeptTreeSelect(
  depts: any,
  parentKey: string,
  idName = 'id'
) {
  return depts.map((dept: any, index: any) => {
    return {
      title: dept.dept_name,
      key: dept[parentKey],
      id: dept[idName],
      icon: () =>
        h(SvgIcon, {
          class: 'icon',
          style: {
            width: '1.2em',
            height: '1.2em',
          },
          name: 'bumen3',
        }),
      children: transformDeptTreeSelect(dept.children || [], parentKey, idName),
    };
  });
}

export function deepTree(
  name: string,
  depts: any,
  parentKey: string,
  idName = 'id',
  icon: 'bumen3'
) {
  return depts.map((dept: any, index: any) => {
    return {
      title: dept[name],
      key: dept[parentKey],
      id: dept[idName],
      icon: () =>
        h(SvgIcon, {
          class: 'icon',
          style: {
            width: '1.2em',
            height: '1.2em',
          },
          name: icon,
        }),
      children: deepTree(name, dept.children || [], parentKey, idName, icon),
    };
  });
}

export function replaceZeroWithEmpty(obj: any) {
  if (typeof obj !== 'object' || obj === null) return obj;

  if (Array.isArray(obj)) {
    return obj.map((item) => replaceZeroWithEmpty(item));
  }

  return Object.entries(obj).reduce((acc: any, [key, value]) => {
    if (value === 0) {
      acc[key] = '';
    } else if (typeof value === 'object' && value !== null) {
      acc[key] = replaceZeroWithEmpty(value);
    } else {
      acc[key] = value;
    }
    return acc;
  }, {});
}

export function findIdByKey(treeData: any, targetKey: any) {
  const stack = [...treeData];

  while (stack.length) {
    const node = stack.pop();
    // 匹配当前节点的key
    if (node?.key === targetKey) {
      return node.id;
    }
    // 处理子节点
    if (node?.children?.length) {
      stack.push(...node.children);
    }
  }
  return null;
}

interface optionType {
  userData: any;
  labelName: string;
  valueName: string;
}

// 处理options数据
export function transformUserData(params: optionType) {
  const { userData, labelName, valueName } = params;
  return userData.map((item: any) => ({
    label: item[labelName],
    value: item[valueName],
  }));
}

export function getLabelByValue(targetValue: any) {
  const sex = [
    { label: '', value: 1 },
    { label: '男', value: 2 },
    { label: '女', value: 3 },
  ];
  return sex.reduce((result, item) => {
    if (item.value === targetValue) {
      return item.label;
    }
    return result;
  }, null);
}

export const collectAllKeys = (nodes: any) => {
  return nodes.flatMap((node: any) => {
    let keys = [node.key];
    // 检查 children 是否为数组
    if (Array.isArray(node.children)) {
      keys = keys.concat(collectAllKeys(node.children));
    }
    return keys;
  });
};

export function transformNodeAssignee(obj) {
  // 遍历对象所有属性
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];

      // 处理 node_assignee_list 数组
      if (key === 'node_assignee_list' && Array.isArray(value)) {
        obj[key] = value.map((id) => ({ id }));
      }
      // 递归处理子对象（包括 child_node 或其他嵌套对象）
      else if (typeof value === 'object' && value !== null) {
        // 处理数组中的对象（如 child_node 可能是数组）
        if (Array.isArray(value)) {
          value.forEach((item) => transformNodeAssignee(item));
        }
        // 处理单个对象（如 child_node 是单个对象）
        else {
          transformNodeAssignee(value);
        }
      }
    }
  }
  return obj;
}

export function openFilePreviewInNewPage(fileUrl: string, title?: string) {
  // 验证文件URL有效性
  if (!fileUrl || !/^https?:\/\//.test(fileUrl)) {
    console.error('文件URL无效，请提供有效的HTTP/HTTPS链接');
    alert('文件地址无效，请检查链接是否正确');
    return;
  }

  // 对文件URL进行编码（处理特殊字符）
  const encodedFileUrl = encodeURIComponent(fileUrl);
  // 微软在线预览地址
  const microsoftPreviewUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodedFileUrl}`;

  // 创建新页面
  const newWindow = window.open('', '_blank');
  if (!newWindow) {
    console.error('浏览器阻止了新窗口弹出，请允许弹出窗口');
    alert('请允许弹出窗口以预览文件');
    return;
  }

  // 写入新页面内容（自定义标题和加载状态）
  newWindow.document.write(`
    <!DOCTYPE html>
    <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${title || '文件预览'}</title>
        <style>
          * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
          }
          body, html {
            width: 100%;
            height: 100%;
            overflow: hidden;
          }
          .loading-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #fff;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 9999;
          }
          .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16px;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
          iframe {
            width: 100%;
            height: 100%;
            border: none;
          }
          .error-message {
            color: #e74c3c;
            font-size: 16px;
            text-align: center;
            padding: 20px;
          }
        </style>
      </head>
      <body>
        <!-- 加载状态 -->
        <div class="loading-container" id="loading">
          <div class="spinner"></div>
          <p>正在加载文件，请稍候...</p>
        </div>

        <!-- 预览iframe -->
        <iframe 
          src="${microsoftPreviewUrl}" 
          onload="document.getElementById('loading').style.display='none'"
          onerror="document.getElementById('loading').innerHTML='<div class=\'error-message\'>文件预览失败，请检查文件链接是否有效</div>'"
        ></iframe>
      </body>
    </html>
  `);

  // 完成文档写入
  newWindow.document.close();
}

import router from '@/router';
export const toDetail = (data: any) => {
  let item = JSON.parse(JSON.stringify(data));
  if (item.policy_content) {
    router.push({
      path: '/ai/policy/policydateDetail',
      query: {
        id: item.policy_id,
      },
    });
  } else {
    //   预览文件
    const downloading = ref(false); // 定义一个加载状态变量
    item.policy_file = `${import.meta.env.VITE_API_BASE_URL}${
      item.policy_file
    }`;
    Modal.confirm({
      title: '系统提示',
      content: '是否需要下载政策文件？',
      okText: '确认',
      onOk: () => {
        if (downloading.value) return; // 防止重复点击
        downloading.value = true;
        // 打开下载链接
        window.open(item.policy_file);
        // 3秒后自动关闭加载状态（根据实际需求调整）
        setTimeout(() => {
          downloading.value = false;
        }, 3000);
      },
      cancelText: '取消',
      // 禁用确认按钮（可选，结合loading状态使用）
      okButtonProps: {
        loading: downloading.value,
      },
    });
    // window.open(item.policy_file);

    // router.push({
    //   path: '/ai/policy/review',
    //   query: {
    //     file: item.policy_file,
    //   },
    // });
  }
};
